#ifndef __ImageConvert_H_
#define __ImageConvert_H_


/*
// Return minimum and maximum of the input image
template <class T>
void getMinMaxImage(const pip::Image<T> &in, T &min, T &max)
{
  min = numeric_limits<T>::max();
  max = numeric_limits<T>::min();

  for (int z = 0; z < in.dim(2); ++z) {
    for (int y = 0; y < in.dim(1); ++y) {
      for (int x = 0; x < in.dim(0); ++x) {
        T value(in(x, y, z));

        if (value > max) {
          max = value;
        }

        if (value < min) {
          min = value;
        }
      }
    }
  }
}
*/
template <class T>
pip::Image<unsigned char> convertAllToUnsignedChar(const pip::Image<T> &input)
{
  pip::Image<unsigned char> output;
  T min, max;
  getMinMaxImage(input, min, max);

  output.resize(input.dimension());

  if (min == max) {
    output.fill(128);
    return output;
  }
  
  float scale( float(numeric_limits<unsigned char>::max()) / (max - min));
  //std::cout << int(max - min) << "   \n";
  //std::cout << int(T(numeric_limits<unsigned char>::max())) << "   \n";
  //std::cout << scale << "   \n";
  for (int z = 0; z < input.dim(2); ++z) {
    for (int y = 0; y < input.dim(1); ++y) {
      for (int x = 0; x < input.dim(0); ++x) {
		  //std::cout << int(unsigned char((scale * (input(x, y, z) - min))))<< "   ";
        output(x, y, z) = (unsigned char)(scale * (input(x, y, z) - min));
      }
    }
  }
  return output;
}

#endif